<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FilesController extends Controller
{
    public function upload(Request $request)
    {
        $file = $request->file("file");
        if ($file->isValid()) {
            $entension = $file->getClientOriginalExtension(); //上传文件的后缀
            $newName = date('YmdHis') . mt_rand(100, 900) . '.' . $entension; //设置图片上传之后的名字。
            $path = $file->move(public_path() . '/uploads\/', $newName); //移动图片到指定地址

            if ($request->post("id")) {
                $res = DB::table("imgs")->where("id", $request->post("id"))->update(["name" => $newName, "url" => "/uploads/" . $newName]);
            } else {
                //添加insertGetId
                $res = DB::table('imgs')->insertGetId([
                    "url" => "/uploads/" . $newName,
                    'name' => $newName,
                ]);
            }
            //判断是否添加成功
            if (!$res) {
                return $this->errorJson(-3, '添加失败');
            }
            //成功返回
            return json_encode(["code" => 200, "msg" => "success", "data" => [
                "url" => $_SERVER["APP_URL"] . "img/download/" . $newName,
                "name" => $newName,
                "id" => $res,
            ]]); //返回图片的临时路径
        }
    }

    public function download($filename)
    {
        $img = "./uploads/" . basename($filename);
        header('Content-Disposition:attachment;filename=' . $img);
        readfile($img);
    }
    //失败返回函数
    public function errorJson($code, $msg)
    {
        return json_encode(["code" => $code, 'msg' => $msg]);
    }
}
